import { Component, OnInit, Input, DoCheck, Output, EventEmitter, TemplateRef } from '@angular/core'

import { IBaseInfoColumn, HoverType } from '@shared/interfaces/baseInfo'
import { PageService } from '@shared/services/page.service'

@Component({
  selector: 'app-base-info',
  templateUrl: './base-info.component.html',
  styleUrls: ['./base-info.component.less'],
})
export class BaseInfoComponent implements OnInit {
  public infoItemClass: string[] = []

  private hoveredColumn: IBaseInfoColumn | null

  private allColumns: IBaseInfoColumn[] = []

  @Input() imgSrc: string

  @Input() imgTpl: TemplateRef<void> // 左侧图片支持组件传入, 但是和 src 不能同时传入

  @Input() firstSecondHeight: number // 第一行和第二行的高度，默认160，但支持自定义

  @Input() totalHeight: number // 总的高度，默认是 341, 支持自定义，与 firstSecondHeight 配合使用

  @Output() firstColumnsChange = new EventEmitter<IBaseInfoColumn[]>()
  @Input() firstColumns: IBaseInfoColumn[] = []

  @Output() secondColumnsChange = new EventEmitter<IBaseInfoColumn[]>()
  @Input() secondColumns: IBaseInfoColumn[] = []

  @Output() bottomColumnsRowsChange = new EventEmitter<Array<IBaseInfoColumn[]>>()
  @Input() bottomColumnsRows: Array<IBaseInfoColumn[]> = []

  @Input() allowEdit = true

  ifEdit: boolean

  constructor(private pageService: PageService) {}

  ngOnInit() {
    this.collectAllColumns()
    this.pageService.isBaseEdit$.subscribe(this.handleEdit.bind(this))
  }

  handleEdit(ifEdit: boolean): void {
    this.ifEdit = ifEdit
    if (ifEdit) {
      this.collectAllColumns()
      this.makeFirstItemActive()
    } else if (this.hoveredColumn) {
      this.hoveredColumn.hover = HoverType.Normal
      this.hoveredColumn = null
    }
  }

  collectAllColumns(): void {
    this.allColumns = [].concat(this.firstColumns, this.secondColumns, ...this.bottomColumnsRows)
    // set the colum id here.
    this.allColumns.forEach((column, index) => (column.id = index))
  }

  makeFirstItemActive(): void {
    const firstEditableColumn = this.allColumns.find(column => !column.disEditable)
    if (firstEditableColumn) {
      this.activeItem(firstEditableColumn.id)
    }
  }

  activeItem(id: number) {
    if (!this.ifEdit) return
    const targetColumn = this.allColumns.find(column => column.id === id)
    if (targetColumn) {
      if (this.hoveredColumn) this.disActiveColumn(this.hoveredColumn)
      this.activeColumn(targetColumn)
      this.hoveredColumn = targetColumn
    }
  }

  private activeColumn(column: IBaseInfoColumn, target?: EventTarget) {
    /* 激活选项，有几步操作：
      1. 给外边框增加高亮
      2. 里面的 input 进入激活状态，并且鼠标移动到尾部
     */
    if (column.hover !== HoverType.Error) {
      column.hover = HoverType.Active
    }
  }

  private disActiveColumn(column: IBaseInfoColumn) {
    /*
      激活的反向操作
     */
    if (column.hover !== HoverType.Error) {
      column.hover = HoverType.Normal
    }
  }
}
